package com.mvp.shq.washer.ui.main;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.activity.CaptureActivity;
import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.APP;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.download.DownloadService;
import com.mvp.shq.washer.entity.BaseEvent;
import com.mvp.shq.washer.entity.VersionBean;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.rxbus.ThreadMode;
import com.mvp.shq.washer.ui.coupon.CouponActivity;
import com.mvp.shq.washer.ui.home.HomeFragment;
import com.mvp.shq.washer.ui.login.LoginActivity;
import com.mvp.shq.washer.ui.mine.MineFragment;
import com.mvp.shq.washer.ui.order.OrderFragment;
import com.mvp.shq.washer.ui.recharge.RechargeFragment;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StatusBarLightMode;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.CustomDialog;
import com.orhanobut.logger.Logger;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

public class MainActivity extends BaseActivity<MainPresenter,MainModel> implements MainConstract.View {
    @BindView(R.id.vp_main)
    ViewPager vpMain;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    //tab 文字
    private final int[] TAB_TITLES = new int[]{R.string.tab_home,R.string.tab_recharge,R.string.tab_order,R.string.tab_mine};
    //tab 图片
    private final int[] TAB_IMGS = new int[]
            {R.drawable.tab_home_selector,R.drawable.tab_recharge_selector,R.drawable.tab_order_selector,R.drawable.tab_mine_selector};
    //Fragment数组
    private final Fragment[] TAB_FRAGMENTS = new Fragment[]
            {new HomeFragment(),new RechargeFragment(),new OrderFragment(),new MineFragment()};
    //Tab数量
    private final int TAB_COUNT = TAB_TITLES.length;
    private ImageView[] tabImg = new ImageView[TAB_COUNT];
    private MyViewPagerAdapter mAdapter;
    private CustomDialog dlDialog;
    private DownloadService.DownloadBinder mDownloadBinder;
    private String APK_URL = "";
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mDownloadBinder = (DownloadService.DownloadBinder) service;
            mDownloadBinder.setInstallMode(false);
            long downloadId = mDownloadBinder.startDownload(APK_URL);
            startCheckProgress(downloadId);
            dlDialog.dismiss();
            T.show("后台开始下载");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mDownloadBinder = null;
        }
    };
    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        init();
        StatusBarLightMode.StatusBarLightMode(this);
        getUserInfo();
        presenter.banner();
        if (getIntent().getExtras()!=null){
            int jumpKey = getIntent().getExtras().getInt("jumpKey");
            if (jumpKey == EventCode.TO_MSG){
                JumpUtil.toNews(context);
            }else if (jumpKey == EventCode.TO_COUPON){
                JumpUtil.toCoupon(context,CouponActivity.CHECK);
            }
        }

    }
    @Subscribe(code = EventCode.UPDATE_JPUSH_ALIAS)
    public void setAlias(){
        presenter.setAlias();
    }

    private void init() {
        initTabs();
    }

    private void initTabs(){
        setTabs(tablayout,this.getLayoutInflater(),TAB_TITLES,TAB_IMGS);
        mAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        vpMain.setAdapter(mAdapter);
        vpMain.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
        tablayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(vpMain));
        vpMain.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position){
                    case 0:
                        StatusBarUtil.setColor(MainActivity.this,getResources().getColor(R.color.home_status_bar),0);
                        break;
                    case 1:
                        StatusBarUtil.setColor(MainActivity.this,getResources().getColor(R.color.white),6);
                        break;
                    case 2:
                        StatusBarUtil.setColor(MainActivity.this,getResources().getColor(R.color.white),6);
                        break;
                    case 3:
                        StatusBarUtil.setColor(MainActivity.this,getResources().getColor(R.color.white),6);
                        break;
                }
                Animation animation = AnimationUtils.loadAnimation(context,R.anim.tab_scale);
                tabImg[position].setAnimation(animation);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        StatusBarUtil.setColor(this,getResources().getColor(R.color.home_status_bar),0);

    }
    /**
     * @description: 设置添加Tab
     */
    private void setTabs(TabLayout tabLayout, LayoutInflater inflater, int[] tabTitlees, int[] tabImgs){
        for (int i = 0; i < tabImgs.length; i++) {
            TabLayout.Tab tab = tabLayout.newTab();
            View view = inflater.inflate(R.layout.tab_custom,null);
            tab.setCustomView(view);
            TextView tvTitle = (TextView)view.findViewById(R.id.tv_tab);
            tvTitle.setText(tabTitlees[i]);
            ImageView imgTab = (ImageView) view.findViewById(R.id.img_tab);
            imgTab.setImageResource(tabImgs[i]);
            tabImg[i] = imgTab;
            tabLayout.addTab(tab);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 66){
            tablayout.getTabAt(1).select();
        }
    }
    @Subscribe(code = EventCode.TO_MESSAGE,threadMode = ThreadMode.MAIN)
    public void toMessage(){
        Logger.d("跳转到系统消息");
        JumpUtil.toNews(context);
    }
    @Subscribe(code = EventCode.TO_COUPON,threadMode = ThreadMode.MAIN)
    public void toCoupon(){
        Logger.d("跳转到优惠券");
        JumpUtil.toCoupon(context, CouponActivity.CHECK);
    }

    @Subscribe(code = EventCode.GET_USER_INFO)
    public void getUserInfo(){
        if (SpUtil.getUser() == null){
            return;
        }
        presenter.getUserInfo();
    }

    @Override
    public void updateAPK(VersionBean versionBean) {
        APK_URL = versionBean.getDownloadUrl();
        if (dlDialog == null){
            CustomDialog.Builder builder = new CustomDialog.Builder(context);
            dlDialog = builder.setMessage("请升级APP至"+versionBean.getVersionCode()+"版本")
                    .setNegativeButton("确认升级", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, DownloadService.class);
                            startService(intent);
                            bindService(intent, mConnection, BIND_AUTO_CREATE);//绑定服务

                        }
                    })
                    .setPositiveButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dlDialog.dismiss();
                        }
                    }).createTwoButtonDialog();
        }
        dlDialog.show();
    }
    @Subscribe(code = EventCode.SET_JPUSH_ALIAS)
    public void setJpushAlias(){
        presenter.setAlias();
    }
    private class MyViewPagerAdapter extends FragmentPagerAdapter {
        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return TAB_FRAGMENTS[position];
        }

        @Override
        public int getCount() {
            return TAB_COUNT;
        }
    }
    private void startCheckProgress(long downloadId) {
        Observable
                .interval(100, 200, TimeUnit.MILLISECONDS, Schedulers.io())//无限轮询,准备查询进度,在io线程执行
                .filter(times -> mDownloadBinder != null)
                .map(i -> mDownloadBinder.getProgress(downloadId))//获得下载进度
                .takeUntil(progress -> progress >= 100)//返回true就停止了,当进度>=100就是下载完成了
                .distinct()//去重复
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressObserver());
    }
    //观察者
    private class ProgressObserver implements Observer<Integer> {

        @Override
        public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

        }

        @Override
        public void onNext(Integer progress) {
            //mProgressBar.setProgress(progress);//设置进度
            //L.d("下载进度："+progress);
        }
        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
            Toast.makeText(MainActivity.this, "下载出错", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onComplete() {
            String url = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+"/qiaoqiao.apk";
            //InstallUtil.install(context,url,false);
        }
    }
    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                T.show("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                APP.getApp().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
